package com.nibian.nibian.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nibian.nibian.R;
import com.nibian.nibian.activity.MainActivity;
import com.nibian.nibian.app.Umeng;
import com.nibian.nibian.bean.TextBean;
import com.nibian.nibian.ui.ProgressDialogs;
import com.nibian.nibian.utils.CRCUtils;
import com.nibian.nibian.utils.DialogUtils;
import com.nibian.nibian.utils.SharedPreferenceTools;
import com.nibian.nibian.utils.UiUtils;
import com.nibianplus.base.BaseFragment;
import com.nibianplus.base.BaseObject;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @创建者 luck
 * @创建时间 ${DATA} 15:00
 * @描述 ${参数设置}
 * @更新者 $Author$
 * @更新时间 $Date$
 * @更新描述 ${TODO}
 */
public class SheZhiFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.user_defind_rl)
    RelativeLayout user_defind_rl;                  //自定义
    @BindView(R.id.xtdy_tv)
    EditText xtdy_tv;                               //系统电压
    @BindView(R.id.bcrl_tv)
    EditText bcrl_tv;                               //蓄电池容量
    @BindView(R.id.tv_set)
    TextView tv_set;                                //设置
    @BindView(R.id.dclx_tv)
    TextView dclx_tv;                               //自定义
    @BindView(R.id.user_defind_cy)
    EditText user_defind_cy;
    @BindView(R.id.user_defind_cd)
    EditText user_defind_cd;
    @BindView(R.id.user_defind_jh)
    EditText user_defind_jh;
    @BindView(R.id.user_defind_ts)
    EditText user_defind_ts;
    @BindView(R.id.user_defind_fc)
    EditText user_defind_fc;
    @BindView(R.id.user_defind_tsc)
    EditText user_defind_tsc;
    @BindView(R.id.user_defind_gf)
    EditText user_defind_gf;
    @BindView(R.id.user_defind_qy)
    EditText user_defind_qy;
    @BindView(R.id.user_defind_gfd)
    EditText user_defind_gfd;
    @BindView(R.id.user_defind_fd)
    EditText user_defind_fd;
    @BindView(R.id.user_defind_gfy)
    EditText user_defind_gfy;
    @BindView(R.id.user_defind_jhc)
    EditText user_defind_jhc;
    @BindView(R.id.user_defind_tscd)
    EditText user_defind_tscd;
    @BindView(R.id.user_defind_jhcd)
    EditText user_defind_jhcd;
    @BindView(R.id.user_defind_wd)
    EditText user_defind_wd;
    @BindView(R.id.btCy)
    Button btCy;
    @BindView(R.id.btCd)
    Button btCd;
    @BindView(R.id.btjh)
    Button btjh;
    @BindView(R.id.btfc)
    Button btfc;
    @BindView(R.id.btsy)
    Button btsy;
    @BindView(R.id.btonlysy)
    Button btonlysy;

    private Dialog loading;     //加载狂
    private Dialog mSettingLoading;
    private boolean isSetData = false;              //默认第一次自定义为false
    public static SheZhiFragment sSheZhiFragment;
    private String mLanguages_key;
    private Dialog mTypeDialog;
    private TextView tv0;
    private TextView tv1;
    private TextView tv2;
    private TextView tv3;
    private TextView tv4;
    private View mViewDialog;
    private HashMap<Integer, String> mSaveData;
    private int mCount;
    private int mTryCount;
    public static final int TRY_COUT = 10;
    private View mInflate;

    public static SheZhiFragment getInstance() {
        return sSheZhiFragment;
    }
//    private DataCanShu dataCanShu = new DataCanShu();

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        sSheZhiFragment = this;
        mLanguages_key = SharedPreferenceTools.getString(UiUtils.getContext(), "LANGUAGES_KEY", "zh");
        if (mInflate == null) {
            mInflate = View.inflate(UiUtils.getContext(), R.layout.set_data, null);
            ButterKnife.bind(this, mInflate);
            mSaveData = new HashMap<>();
            MainActivity.getInstance().sendSheZhiData();
            MainActivity.getInstance().showJianKongFra();
        }
        return mInflate;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (savedInstanceState != null) {
            ArrayList<HashMap<Integer, String>> list = (ArrayList<HashMap<Integer, String>>) savedInstanceState.getSerializable("HASHMAP");
            if (list != null) {
                HashMap<Integer, String> hashMap = list.get(0);
                for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
                    setUiData2(entry.getValue(), entry.getKey());
                }
            }
        }

        if (mLanguages_key.equals("zh")) {
            loading = ProgressDialogs.getLoading(getActivity(), "正在加载...");
        } else {
            loading = ProgressDialogs.getLoading(getActivity(), "loading...");
        }
        if (mLanguages_key.equals("zh")) {
            mSettingLoading = ProgressDialogs.getLoading(getActivity(), "正在加载...", false);
        } else {
            mSettingLoading = ProgressDialogs.getLoading(getActivity(), "loading...", false);
        }
        loading.show();
        mViewDialog = View.inflate(getActivity(), R.layout.dialog_type, null);
        mTypeDialog = DialogUtils.showCustomDialog(getActivity(), mViewDialog, R.style.custom_dialog_style, 0, 0.8f, Gravity.CENTER);
        tv0 = (TextView) mViewDialog.findViewById(R.id.tv0);
        tv1 = (TextView) mViewDialog.findViewById(R.id.tv1);
        tv2 = (TextView) mViewDialog.findViewById(R.id.tv2);
        tv3 = (TextView) mViewDialog.findViewById(R.id.tv3);
        tv4 = (TextView) mViewDialog.findViewById(R.id.tv4);
        tv0.setOnClickListener(this);
        tv1.setOnClickListener(this);
        tv2.setOnClickListener(this);
        tv3.setOnClickListener(this);
        tv4.setOnClickListener(this);
    }

    /**
     * diolog
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (loading != null) {
            loading.cancel();
        }
        if (mSettingLoading != null) {
            mSettingLoading.cancel();
        }
    }

    /**
     * 事件处理
     *
     * @param view
     */
    @OnClick({
            R.id.dclx_tv,
            R.id.user_defind_rl, R.id.user_defind_cy, R.id.user_defind_cd, R.id.user_defind_jh, R.id.user_defind_ts, R.id.user_defind_fc, R.id.user_defind_jhc, R.id.user_defind_tscd,
            R.id.user_defind_tsc, R.id.user_defind_gf, R.id.user_defind_qy, R.id.user_defind_gfd, R.id.user_defind_fd, R.id.user_defind_gfy, R.id.user_defind_jhcd, R.id.user_defind_wd,
            R.id.tv_set, R.id.btCy, R.id.btCd, R.id.btjh, R.id.btfc, R.id.btsy, R.id.btonlysy})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_defind_rl:               //自定义的点击事件
                break;
            case R.id.tv_set:                       //弹出dialog - 用来校验密码的正确性 - 正确的密码可以进行对数据的修改
                if (isSetData) {
                    isSetData = false;
                    String tvSet;
                    if (mLanguages_key.equals("zh")) {
                        tvSet = "set";
                    } else {
                        tvSet = "设置";
                    }
                    tv_set.setText(tvSet);
                    userSetData();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mSettingLoading.isShowing() && !getActivity().isFinishing()) {
                                mSettingLoading.dismiss();
                                UiUtils.toast("设置失败");
                            }
                        }
                    }, 15000);
                } else {
                    checkPsw();
                }
                break;
            case R.id.dclx_tv:
                mTypeDialog.show();
                break;
            case R.id.tv0:
                String tv0Str;
                if (mLanguages_key.equals("zh")) {
                    tv0Str = "自定义";
                } else {
                    tv0Str = "User-defined";
                }
                setType(tv0Str);
                dismissDialog();
                break;
            case R.id.tv1:
                String tv1Str;
                if (mLanguages_key.equals("zh")) {
                    tv1Str = "开口";
                } else {
                    tv1Str = "Open lead acid battery";
                }
                setType(tv1Str);
                dismissDialog();
                break;
            case R.id.tv2:
                String tv2Str;
                if (mLanguages_key.equals("zh")) {
                    tv2Str = "密封";
                } else {
                    tv2Str = "Sealed battery";
                }
                setType(tv2Str);
                dismissDialog();
                break;
            case R.id.tv3:
                String tv3Str;
                if (mLanguages_key.equals("zh")) {
                    tv3Str = "胶体";
                } else {
                    tv3Str = "gel battery";
                }
                setType(tv3Str);
                dismissDialog();
                break;
            case R.id.tv4:
                String tv4Str;
                if (mLanguages_key.equals("zh")) {
                    tv4Str = "锂电池";
                } else {
                    tv4Str = "LiFeO4 battery";
                }
                setType(tv4Str);
                dismissDialog();
                break;
            case R.id.btCy:
                String data = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0106e0050096")));
                byte[] bytes = CRCUtils.hexString2Bytes("ffff02080106e0050096" + data + "aaaa");
                MainActivity.getInstance().sendChangeData(bytes);                   //--1
                break;
            case R.id.btCd:
                String datacd = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0106e0060096")));
                byte[] bytescd = CRCUtils.hexString2Bytes("ffff02080106e0060096" + datacd + "aaaa");
                MainActivity.getInstance().sendChangeData(bytescd);
                break;
            case R.id.btjh:
                String datajh = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0110" + "E007" + "000204" + "0096" + "0096")));
                byte[] bytesjh = CRCUtils.hexString2Bytes("FFFF020D0110" + "E007" + "000204" + "0096" + "0096" + datajh + "AAAA");
                MainActivity.getInstance().sendChangeData(bytesjh);
                break;
            case R.id.btfc:
                String datafc = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0110" + "E009" + "000204" + "0096" + "0096")));
                byte[] bytesfc = CRCUtils.hexString2Bytes("FFFF020D0110" + "E009" + "000204" + "0096" + "0096" + datafc + "AAAA");
                MainActivity.getInstance().sendChangeData(bytesfc);
                break;
            case R.id.btsy:
                byte[] bytessy = CRCUtils.hexString2Bytes("ffff022e0110e00200132600c8ff00000000960096009600960096009600960096009600966432000500780078001e0003e791aaaa");
                MainActivity.getInstance().sendChangeData(bytessy);
                break;
            case R.id.btonlysy:
                String dataonlysy = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0110" + "e005" + "000a14" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096")));
                byte[] bytesonlysy = CRCUtils.hexString2Bytes("FFFF021d" + "0110" + "e005" + "000a14" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + "0096" + dataonlysy + "AAAA");
                MainActivity.getInstance().sendChangeData(bytesonlysy);
                break;

        }
    }

    private void dismissDialog() {
        if (mTypeDialog != null) {
            mTypeDialog.dismiss();
        }
    }

    private void setType(String type) {
        dclx_tv.setText(type);
    }

    /**
     * 校验密码
     */
    private void checkPsw() {
        String hint;
        String message;
        String cancel;
        String confirm;
        final String hintEmpty;
        final String save;
        if (mLanguages_key.equals("zh")) {
            hint = "设备断开连接";
            message = "自定义数据请进行密码验证";
            cancel = "取消";
            confirm = "确定";
            hintEmpty = "请完成密码验证";
            save = "保存";
        } else {
            hint = "TIPS";
            message = "Please enter password for verification of customized data";
            cancel = "Cancel";
            confirm = "OK";
            hintEmpty = "Please complete the password verification";
            save = "save";
        }
        final EditText editText = new EditText(getActivity());
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle(hint)
                .setMessage(message)
                .setView(editText, 70, 0, 70, 0)
                .setPositiveButton(confirm, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (TextUtils.isEmpty(editText.getText().toString())) {
                            UiUtils.toast(hintEmpty);
                        } else {
                            if (TextUtils.equals(editText.getText().toString(), "nibian")) {
                                isSetData = true;
                                UiUtils.toast("验证成功，可点击修改");
                                setEditTextEnable();
                                tv_set.setText(save);
                                //---------
//                                if (mLanguages_key.equals("zh")) {
//                                    dclx_tv.setText("保存");
//                                } else {
//                                    dclx_tv.setText("save");
//                                }
                            } else {
                                UiUtils.toast("密码验证错误");
                            }
                        }
                    }
                }).setNegativeButton(cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create();                                                                // 创建对话框
        alertDialog.show();                                                                         // 显示对话框
    }

    /**
     * 设置可以被点击
     */
    private void setEditTextEnable() {
        user_defind_cy.setEnabled(true);
        user_defind_cd.setEnabled(true);
        user_defind_jh.setEnabled(true);
        user_defind_ts.setEnabled(true);
        user_defind_fc.setEnabled(true);
        user_defind_tsc.setEnabled(true);
        user_defind_gf.setEnabled(true);
        user_defind_qy.setEnabled(true);
        user_defind_gfd.setEnabled(true);
        user_defind_fd.setEnabled(true);
        user_defind_gfy.setEnabled(true);
        user_defind_jhc.setEnabled(true);
        user_defind_tscd.setEnabled(true);
        user_defind_jhcd.setEnabled(true);
        user_defind_wd.setEnabled(true);
        bcrl_tv.setEnabled(true);
        dclx_tv.setEnabled(true);
    }

    @Override
    public void refreshUI(BaseObject object, int what) {
    }

    @Override
    protected BaseObject createDataObject() {
        return TextBean.getInstance(getTagName());
    }


    public void setUiData2(String data, int dataCount) {
        //[ffff000c5452414e53504f52543d320daaaa, ffff0207010302007979a6aaaa, ffff0209010304004b00794bc7aaaa,
        // ffff 0209 0103 04 00aa 009b 9bb8 aaaa, ffff0209010304009800907bb0aaaa, ffff0209010304008a007e5bf9aaaa,
        // ffff0209010304007e00789a09aaaa, ffff0209010304006e00695bc0aaaa, ffff020901030400050078ea10aaaa,
        // fff02090103040078001efa22aaaa, ffff0209010304000300040bf0aaaa]
        mSaveData.put(dataCount, data);
        if (dataCount == 0) {
            //ffff0207010302 007a 39a7 aaaa
            String substring2 = data.substring(16, 18);                       //读蓄电池电压
            String xtdy = String.format("%.1f", UiUtils.toTen(substring2) * 0.1);
            xtdy_tv.setText(xtdy);
        } else if (dataCount == 1) {
            //ffff 0209 0103 04 0050 007a 7bc1 aaaa
            String substring3 = data.substring(14, 18);                       //读蓄电池容量
            int xdcrl = UiUtils.toTen(substring3);
            bcrl_tv.setText(xdcrl + "");
//                dataCanShu.setXdcrl(xdcrl+"");
        } else if (dataCount == 2) {
            //超压电压 - 充电限制电压56 - ffff 0209 0103 04 00aa 009b 9bb8 aaaa
            String cydy = data.substring(14, 18);
            String cydys = String.format("%.1f", UiUtils.toTen(cydy) * 0.1);
            user_defind_cy.setText(cydys);

            String cdxzdy = data.substring(18, 22);
            String cdxzdys = String.format("%.1f", UiUtils.toTen(cdxzdy) * 0.1);
            user_defind_cd.setText(cdxzdys);
        } else if (dataCount == 3) {
            //均衡充电电压 - 提升充电电压78 -  ffff0209010304009800907bb0aaaa
            String jhcd = data.substring(14, 18);
            String jhcds = String.format("%.1f", UiUtils.toTen(jhcd) * 0.1);
            String tscd = data.substring(18, 22);
            String tscds = String.format("%.1f", UiUtils.toTen(tscd) * 0.1);
            user_defind_jh.setText(jhcds);
            user_defind_ts.setText(tscds);
        } else if (dataCount == 4) {
            //浮充充电电压 - 提升充电返回电压9A -  ffff0209010304008a007e5bf9aaaa
            String fccd = data.substring(14, 18);
            String fccds = String.format("%.1f", UiUtils.toTen(fccd) * 0.1);
            String tscdfh = data.substring(18, 22);
            String tscdfhs = String.format("%.1f", UiUtils.toTen(tscdfh) * 0.1);
            user_defind_fc.setText(fccds);
            user_defind_tsc.setText(tscdfhs);
        } else if (dataCount == 5) {
            //过房返回电压 -   欠压警告电压BC - ffff0209010304007e00789a09aaaa
            String gffhdy = data.substring(14, 18);
            String gffhdys = String.format("%.1f", UiUtils.toTen(gffhdy) * 0.1);
            String qyjg = data.substring(18, 22);
            String qyjgs = String.format("%.1f", UiUtils.toTen(qyjg) * 0.1);
            user_defind_gf.setText(gffhdys);
            user_defind_qy.setText(qyjgs);
        } else if (dataCount == 6) {
            //过放电压 -   放电限制电压DE - ffff0209010304006e00695bc0aaaa
            String gfdy = data.substring(14, 18);
            String gfdys = String.format("%.1f", UiUtils.toTen(gfdy) * 0.1);
            String fdxzdy = data.substring(18, 22);
            String fdxzdys = String.format("%.1f", UiUtils.toTen(fdxzdy) * 0.1);
            user_defind_gfd.setText(gfdys);
            user_defind_fd.setText(fdxzdys);
        } else if (dataCount == 7) {
//过放延时时间 -   均衡充电时间1011 - ffff020901030400050078ea10aaaa
            String gfys = data.substring(14, 18);
            int gfyss = UiUtils.toTen(gfys);
            String jhcdsj = data.substring(18, 22);
            int jhcdsjs = UiUtils.toTen(jhcdsj);
            user_defind_gfy.setText(gfyss + "");
            user_defind_jhc.setText(jhcdsjs + "");
        } else if (dataCount == 8) {
            //提升充电时间 -   均衡充电间隔1213 - ffff02090103040078001efa22aaaa
            String tscdsj = data.substring(14, 18);
            int tscdsjs = UiUtils.toTen(tscdsj);
            String jhcdjg = data.substring(18, 22);
            int jhcdjgs = UiUtils.toTen(jhcdjg);
            user_defind_tscd.setText(tscdsjs + "");
            user_defind_jhcd.setText(jhcdjgs + "");
        } else if (dataCount == 9) {
            //温度系数14                         ffff0209010304000300040bf0aaaa
            String wdxs = data.substring(14, 18);
            int wdxss = UiUtils.toTen(wdxs);
            user_defind_wd.setText(wdxss + "");
        } else if (dataCount == 10) {
            // 储蓄电池类型
            String wxdc = data.substring(14, 18);
            int wxdcc = UiUtils.toTen(wxdc);
            if (wxdcc == 0) {
                dclx_tv.setText("自定义");
            } else if (wxdcc == 1) {
                dclx_tv.setText("开口");
            } else if (wxdcc == 2) {
                dclx_tv.setText("密封");
            } else if (wxdcc == 3) {
                dclx_tv.setText("胶体");
            } else if (wxdcc == 4) {
                dclx_tv.setText("锂电池");
            }
        }
    }

    public void setResult(String extra) {
        MobclickAgent.onEvent(getActivity(), Umeng.SETTING_RESULT, "dataCount ==" + mCount + "  extra_data=" + extra);
        if (CRCUtils.judgeCrc(extra)) {
            extra = extra.toLowerCase();
            if (extra.contains("e002")) {
                UiUtils.toast("设置成功");
                if (!getActivity().isFinishing())
                    mSettingLoading.dismiss();
            }
        }
    }

//    private void handleToast() {
//        MobclickAgent.onEvent(getActivity(), Umeng.SETTING_FAIL, "count == " + mCount);
//
//        String msg = "";
//        if (mCount == 0) {
//            msg = "超压电压和充电限制电压设置失败";
//        } else if (mCount == 1) {
//            msg = "均衡充电电压和提升充电电压设置失败";
//        } else if (mCount == 2) {
//            msg = "浮充充电电压和提升充电返回电压设置失败";
//        } else if (mCount == 3) {
//            msg = "过放返回电压和过放返回电压设置失败";
//        } else if (mCount == 4) {
//            msg = "过放电压和放电限制电压设置失败";
//        } else if (mCount == 5) {
//            msg = "过放延时时间和均衡充电时间设置失败";
//        } else if (mCount == 6) {
//            msg = "提升充电时间和均衡充电间隔设置失败";
//        } else if (mCount == 7) {
//            msg = "蓄电池类型设置失败";
//        } else if (mCount == 8) {
//            msg = "系统电压和蓄电池标称容量设置失败";
//        } else if (mCount == 9) {
//            msg = "温度补偿系数设置失败";
//        }
//        UiUtils.toast(msg);
//    }

//    private void handleSetFail() {
//        handleToast();
//        mTryCount = 0;
//        mCount++;
//    }

//    private void hanleResultFail() {
//        MobclickAgent.onEvent(getActivity(), Umeng.TRY, "setData   " + TRY_COUT);
//        mTryCount++;
//        if (mTryCount > TRY_COUT) {
//            handleSetFail();
//        }
//        handleSet(mCount);
//    }

    private void handleResultSuccess() {
        MobclickAgent.onEvent(getActivity(), Umeng.SETTING_SUCCESS, "Count  == " + mCount);
        mCount++;
        mTryCount = 0;
        handleSet(mCount);
    }


//    public void handleResult(String extra) {
//        extra = extra.toLowerCase();
//        if (mCount == 0) {
//            if (!extra.contains("e005")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 1) {
//            if (!extra.contains("e007")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 2) {
//            if (!extra.contains("e009")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 3) {
//            if (!extra.contains("e00b")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 4) {
//            if (!extra.contains("e00d")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 5) {
//            if (!extra.contains("e010")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 6) {
//            if (!extra.contains("e012")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 7) {
//            if (!extra.contains("e004")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 8) {
//            // TODO: leo 2017/7/4
//            if (!extra.contains("e00b")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        } else if (mCount == 9) {
//            if (!extra.contains("e014")) {
//                hanleResultFail();
//            } else {
//                handleResultSuccess();
//            }
//        }
//
//    }

    public void handleSet() {
        if (TextUtils.isEmpty(user_defind_cy.getText())) {
            UiUtils.toast("超压电压不可为空");
        } else if (TextUtils.isEmpty(user_defind_cd.getText())) {
            UiUtils.toast("充电限制不可为空");
        } else if (TextUtils.isEmpty(user_defind_jh.getText())) {
            UiUtils.toast("均衡充电电压不可为空");
        } else if (TextUtils.isEmpty(user_defind_ts.getText())) {
            UiUtils.toast("提升充电电压不可为空");
        } else if (TextUtils.isEmpty(user_defind_fc.getText())) {
            UiUtils.toast("浮充充电电压不可为空");
        } else if (TextUtils.isEmpty(user_defind_tsc.getText())) {
            UiUtils.toast("提升充电返回电压不可为空");
        } else if (TextUtils.isEmpty(user_defind_gf.getText())) {
            UiUtils.toast("过放返回电压不可为空");
        } else if (TextUtils.isEmpty(user_defind_qy.getText())) {
            UiUtils.toast("欠压警告电压");
        } else if (TextUtils.isEmpty(user_defind_gfd.getText())) {
            UiUtils.toast("过放电压不可为空");
        } else if (TextUtils.isEmpty(user_defind_fd.getText())) {
            UiUtils.toast("放电限制电压不可为空");
        } else if (TextUtils.isEmpty(user_defind_gfy.getText())) {
            UiUtils.toast("过放延时时间不可为空");
        } else if (TextUtils.isEmpty(user_defind_jhc.getText())) {
            UiUtils.toast("均衡充电时间不可为空");
        } else if (TextUtils.isEmpty(user_defind_tscd.getText())) {
            UiUtils.toast("提升充电时间不可为空");
        } else if (TextUtils.isEmpty(user_defind_jhcd.getText())) {
            UiUtils.toast("均衡充电间隔不可为空");
        } else if (TextUtils.isEmpty(bcrl_tv.getText().toString())) {
            UiUtils.toast("蓄电池标称容量不可为空");
        } else if (TextUtils.isEmpty(user_defind_wd.getText())) {
            UiUtils.toast("温度补偿系数不可为空");
        } else {
            String cy = user_defind_cy.getText().toString();
            String cd = user_defind_cd.getText().toString();
            String jh = user_defind_jh.getText().toString();
            String ts = user_defind_ts.getText().toString();
            String fc = user_defind_fc.getText().toString();
            String tscd = user_defind_tsc.getText().toString();
            String gf = user_defind_gf.getText().toString();
            String qy = user_defind_qy.getText().toString();
            String gfdy = user_defind_gfd.getText().toString();
            String fd = user_defind_fd.getText().toString();
            String gfys = user_defind_gfy.getText().toString();
            String jhcd = user_defind_jhc.getText().toString();
            String tscdsj = user_defind_tscd.getText().toString();
            String jhcdjg = user_defind_jhcd.getText().toString();
            String wd = user_defind_wd.getText().toString();
            if (handleData(cy, "超压电压") &&
                    handleData(cd, "充电限制") &&
                    handleData(jh, "均衡充电电压") &&
                    handleData(ts, "提升充电电压") &&
                    handleData(fc, "浮充充电电压") &&
                    handleData(tscd, "提升充电返回电压") &&
                    handleData(gf, "过放返回电压") &&
                    handleData(qy, "欠压警告电压") &&
                    handleData(gfdy, "过放电压") &&
                    handleData(fd, "放电限制电压") &&
                    handleTime(gfys, "过放延时") &&
                    handleTime(jhcd, "均衡充电") &&
                    handleTime2(tscdsj) &&
                    handleTime3(jhcdjg) &&
                    handleWd(wd)
                    ) {
                String bcrl = bcrl_tv.getText().toString();
                String s = dclx_tv.getText().toString();
                int type;
                if (TextUtils.equals(s, "开口")) {
                    type = 1;
                } else if (TextUtils.equals(s, "密封")) {
                    type = 2;
                } else if (TextUtils.equals(s, "胶体")) {
                    type = 3;
                } else if (TextUtils.equals(s, "锂电池")) {
                    type = 4;
                } else {
                    type = 0;
                }
                String e002 = UiUtils.to0XFloat(bcrl);
                String e003 = "FF00";
                String e004 = UiUtils.toSixString(type + "");
                String e005 = UiUtils.to0XMul10(Float.parseFloat(cy));
                String e006 = UiUtils.to0XMul10(Float.parseFloat(cd));
                String e007 = UiUtils.to0XMul10(Float.parseFloat(jh));
                String e008 = UiUtils.to0XMul10(Float.parseFloat(ts));
                String e009 = UiUtils.to0XMul10(Float.parseFloat(fc));
                String e00a = UiUtils.to0XMul10(Float.parseFloat(tscd));
                String e00b = UiUtils.to0XMul10(Float.parseFloat(gf));
                String e00c = UiUtils.to0XMul10(Float.parseFloat(qy));
                String e00d = UiUtils.to0XMul10(Float.parseFloat(gfdy));
                String e00e = UiUtils.to0XMul10(Float.parseFloat(fd));
                String e00f = "6432";
                String e010 = UiUtils.toSixString(gfys);
                String e011 = UiUtils.toSixString(jhcd);
                String e012 = UiUtils.toSixString(tscdsj);
                String e013 = UiUtils.toSixString(jhcdjg);
                String e014 = UiUtils.toSixString(wd);
                String value = "0110E002001326" + e002 + e003 + e004 + e005 + e006 + e007 + e008 + e009 + e00a + e00b + e00c + e00d + e00e + e00f + e010 + e011 + e012 + e013 + e014;
                String data = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes(value)));
                byte[] bytes = CRCUtils.hexString2Bytes("FFFF022F" + value + data + "AAAA");
                MainActivity.getInstance().sendChangeData(bytes);                   //--1
            }
        }
    }

    private boolean handleWd(String wd) {
        int i = Integer.parseInt(wd);
        if (i < 0 || i > 5) {
            UiUtils.toast("温度补偿系数范围：0~5");
            return false;
        }
        return true;
    }

    public void handleSet(int count) {
        if (count == 0) {
            //超压电压 - 充电限制电压56 - 01 10 E005 0002 04 00AA 009B - xxxx
            if (TextUtils.isEmpty(user_defind_cy.getText())) {
                UiUtils.toast("超压电压不可为空");
                mCount++;
                handleSet(mCount);
            } else if (TextUtils.isEmpty(user_defind_cd.getText())) {
                UiUtils.toast("充电限制不可为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s = user_defind_cy.getText().toString();
                String s1 = user_defind_cd.getText().toString();
                byte[] bytes = setData(s, s1, "E005");
                MainActivity.getInstance().sendChangeData(bytes);                   //--1
            }
        } else if (count == 1) {
            //均衡充电电压 - 提升充电电压78
            if (TextUtils.isEmpty(user_defind_jh.getText())) {
                UiUtils.toast("均衡充电电压不可为空");
                mCount++;
                handleSet(mCount);
            } else if (TextUtils.isEmpty(user_defind_ts.getText())) {
                UiUtils.toast("提升充电电压不可为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s = user_defind_jh.getText().toString();
                String s1 = user_defind_ts.getText().toString();
                byte[] bytes = setData(s, s1, "E007");
                MainActivity.getInstance().sendChangeData(bytes);                   //----2
            }
        } else if (count == 2) {
            //浮充充电电压不可为空 - 提升充电返回电压不可为空9A
            if (TextUtils.isEmpty(user_defind_fc.getText())) {
                UiUtils.toast("浮充充电电压不可为空");
                mCount++;
                handleSet(mCount);
            } else if (TextUtils.isEmpty(user_defind_tsc.getText())) {
                UiUtils.toast("提升充电返回电压不可为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s = user_defind_fc.getText().toString();
                String s1 = user_defind_tsc.getText().toString();
                byte[] bytes = setData(s, s1, "E009");
                MainActivity.getInstance().sendChangeData(bytes);                  //----3
            }
        } else if (count == 3) {
            //过房返回电压 -   欠压警告电压BC
            if (TextUtils.isEmpty(user_defind_gf.getText())) {
                UiUtils.toast("过放返回电压不可为空");
                mCount++;
                handleSet(mCount);
            } else if (TextUtils.isEmpty(user_defind_qy.getText())) {
                UiUtils.toast("欠压警告电压");
                mCount++;
                handleSet(mCount);
            } else {
                String s = user_defind_gf.getText().toString();
                String s1 = user_defind_qy.getText().toString();
                byte[] bytes = setData(s, s1, "E00B");
                MainActivity.getInstance().sendChangeData(bytes);                   //----4
            }
        } else if (count == 4) {
            //过放电压 -   放电限制电压DE
            if (TextUtils.isEmpty(user_defind_gfd.getText())) {
                UiUtils.toast("过放电压不可为空");
                mCount++;
                handleSet(mCount);
            } else if (TextUtils.isEmpty(user_defind_fd.getText())) {
                UiUtils.toast("放电限制电压不可为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s = user_defind_gfd.getText().toString();
                String s1 = user_defind_fd.getText().toString();
                byte[] bytes = setData(s, s1, "E00D");
                MainActivity.getInstance().sendChangeData(bytes);                   //----5
            }
        } else if (count == 5) {
            //过放延时时间 -   均衡充电时间1011 -------------------------------------
            if (TextUtils.isEmpty(user_defind_gfy.getText())) {
                UiUtils.toast("过放延时时间不可为空");
                mCount++;
                handleSet(mCount);
            } else if (TextUtils.isEmpty(user_defind_jhc.getText())) {
                UiUtils.toast("均衡充电时间不可为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s = user_defind_gfy.getText().toString();
                String s1 = user_defind_jhc.getText().toString();
                byte[] bytes = setData1(s, s1, "E010");
                MainActivity.getInstance().sendChangeData(bytes);                //----6
            }
        } else if (count == 6) {
            //提升充电时间 -   均衡充电间隔1213---------------------------------------
            if (TextUtils.isEmpty(user_defind_tscd.getText())) {
                UiUtils.toast("提升充电时间不可为空");
                mCount++;
                handleSet(mCount);
            } else if (TextUtils.isEmpty(user_defind_jhcd.getText())) {
                UiUtils.toast("均衡充电间隔不可为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s = user_defind_tscd.getText().toString();
                String s1 = user_defind_jhcd.getText().toString();
                byte[] bytes = setData2(s, s1, "E012");
                MainActivity.getInstance().sendChangeData(bytes);
            }
        } else if (count == 7) {
            // 蓄电池类型
            if (TextUtils.isEmpty(dclx_tv.getText().toString())) {
                UiUtils.toast("蓄电池类型不可以为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s = dclx_tv.getText().toString();
                int type;
                if (TextUtils.equals(s, "开口")) {
                    type = 1;
                } else if (TextUtils.equals(s, "密封")) {
                    type = 2;
                } else if (TextUtils.equals(s, "胶体")) {
                    type = 3;
                } else if (TextUtils.equals(s, "锂电池")) {
                    type = 4;
                } else {
                    type = 0;
                }
                byte[] bytes = setXuDianData(type + "", "E004");
                MainActivity.getInstance().sendChangeData(bytes);
            }
        } else if (count == 8) {
            if (TextUtils.isEmpty(bcrl_tv.getText().toString())) {
                UiUtils.toast("蓄电池标称容量不可为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s1 = bcrl_tv.getText().toString();
                byte[] bytes = setDianYaData(s1, "E002");
                MainActivity.getInstance().sendChangeData(bytes);

            }
        } else if (count == 9) {
            //温度系数14-------------------------------------------------------------
            if (TextUtils.isEmpty(user_defind_wd.getText())) {
                UiUtils.toast("温度补偿系数不可为空");
                mCount++;
                handleSet(mCount);
            } else {
                String s = user_defind_wd.getText().toString();
                byte[] bytes = setData4(s, "0011", "E014");
                MainActivity.getInstance().sendChangeData(bytes);
            }
        }
    }

    private boolean handleData(String data, String value) {
        float i = Float.parseFloat(data);
        if (i < 7 || i > 17) {
            UiUtils.toast(value + "范围：7~17");
            return false;
        }
        return true;
    }

    private boolean handleTime(String data, String value) {
        int i = Integer.parseInt(data);
        if (i < 0 || i > 120) {
            UiUtils.toast(value + "时间范围：0~120");
            return false;
        }
        return true;
    }

    private boolean handleTime2(String data) {
        int i = Integer.parseInt(data);
        if (i < 10 || i > 300) {
            UiUtils.toast("提升充电时间范围：10~300");
            return false;
        }
        return true;
    }

    private boolean handleTime3(String data) {
        int i = Integer.parseInt(data);
        if (i < 0 || i > 255) {
            UiUtils.toast("均衡充电间隔范围：0~255");
            return false;
        }
        return true;
    }


    /**
     * 用户设置数据
     */
    private void userSetData() {
        mCount = 0;
        SharedPreferenceTools.saveInt(UiUtils.getContext(), "isUi", 1111);
        final byte[] permission = new byte[]{(byte) 0xFF, (byte) 0xFF, 0x00, 0x0C, 0x54, 0x52, 0x41, 0x4E, 0x53, 0x50, 0x4F, 0x52, 0x54, 0x3d, 0x32, 0x0D, (byte) 0xAA, (byte) 0xAA};
        MainActivity.getInstance().sendChangeData(permission, false);
    }

    /**
     * 用户设置数据 - "FFFF020D0110 E005 000204" + s2 + s3 +data+"AAAA"
     *
     * @param data1
     * @param data2
     * @param pdu
     * @return
     */
    private byte[] setData(String data1, String data2, String pdu) {
        float i = Float.parseFloat(data1);
        float i1 = Float.parseFloat(data2);
        if (i < 7 || i > 17 || i1 < 7 || i1 > 17) {
            UiUtils.toast("范围：7~17");
            return null;
        }
        String s2 = UiUtils.to0XMul10(i);
        String s3 = UiUtils.to0XMul10(i1);
        String data = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0110" + pdu + "000204" + s2 + s3)));
        byte[] bytes = CRCUtils.hexString2Bytes("FFFF020D0110" + pdu + "000204" + s2 + s3 + data + "AAAA");
        return bytes;
    }

    /**
     * 用户设置数据-过放延时时间 -   均衡充电时间
     *
     * @param data1
     * @param data2
     * @param pdu
     * @return
     */
    private byte[] setData1(String data1, String data2, String pdu) {
        int i = Integer.parseInt(data1);
        int i1 = Integer.parseInt(data2);
        if (i < 0 || i > 120) {
            UiUtils.toast("过放延时时间范围：0~120");
            return null;
        }
        if (i1 < 0 || i1 > 300) {
            UiUtils.toast("均衡充电时间范围：0~300");
            return null;
        }
        String s2 = UiUtils.toSixString(data1);
        String s3 = UiUtils.toSixString(data2);
        String data = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0110" + pdu + "000204" + s2 + s3)));
        byte[] bytes = CRCUtils.hexString2Bytes("FFFF020D0110" + pdu + "000204" + s2 + s3 + data + "AAAA");
        return bytes;
    }

    private byte[] setDianYaData(String data1, String pdu) {
        String s1 = UiUtils.to0XFloat(data1);
        String data = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0106" + pdu + s1)));
        byte[] bytes = CRCUtils.hexString2Bytes("FFFF02080106" + pdu + s1 + data + "AAAA");
        return bytes;
    }


    private byte[] setXuDianData(String data1, String pdu) {
        String s1 = UiUtils.toSixString(data1);
        String data = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0106" + pdu + s1)));
        byte[] bytes = CRCUtils.hexString2Bytes("FFFF02080106" + pdu + s1 + data + "AAAA");
        return bytes;
    }

    /**
     * 用户设置数据-提升充电时间 -   均衡充电间隔
     *
     * @param data1
     * @param data2
     * @param pdu
     * @return
     */
    private byte[] setData2(String data1, String data2, String pdu) {
        int i = Integer.parseInt(data1);
        int i1 = Integer.parseInt(data2);
        if (i < 0 || i > 300) {
            UiUtils.toast("提升充电时间范围：10~300");
            return null;
        }
        if (i1 < 0 || i1 > 255) {
            UiUtils.toast("均衡充电间隔范围：0~255");
            return null;
        }
        String s2 = UiUtils.toSixString(data1);
        String s3 = UiUtils.toSixString(data2);
        String data = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0110" + pdu + "000204" + s2 + s3)));
        byte[] bytes = CRCUtils.hexString2Bytes("FFFF020D0110" + pdu + "000204" + s2 + s3 + data + "AAAA");
        return bytes;
    }

    /**
     * 用户设置数据
     *
     * @param data1
     * @param data2
     * @param pdu
     * @return
     */
    private byte[] setData4(String data1, String data2, String pdu) {
        int i = Integer.parseInt(data1);
        if (i < 0 || i > 5) {
            UiUtils.toast("温度补偿系数范围：0~5");
            return null;
        }
        String s2 = UiUtils.toSixString(data1);
        String s3 = UiUtils.toSixString(data2);
        String data = CRCUtils.getData(CRCUtils.calcCrc16(CRCUtils.hexStringToBytes("0110" + pdu + "000204" + s2 + s3)));
        byte[] bytes = CRCUtils.hexString2Bytes("FFFF020D0110" + pdu + "000204" + s2 + s3 + data + "AAAA");
        return bytes;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (!mSaveData.isEmpty()) {
            ArrayList<HashMap> list = new ArrayList<>();
            list.add(mSaveData);
            outState.putSerializable("HashMap", list);
        }
    }

}
